<?php

/**
 * This is the main controller used by most of the actions from the main screen.
 */
class SiteController extends CController {

  /**
   * Maximum number of slots the application displays on the screen.
   */
  const MAX_SLOTS = 12;

  /**
   * Declares class-based actions.
   */
  public function actions() {
    return array(
            // captcha action renders the CAPTCHA image
            // this is used by the contact page
            'captcha'=>array(
                    'class'=>'CCaptchaAction',
                    'backColor'=>0xEBF4FB,
            ),
    );
  }

  /**
   * Main screen that shows all your projects and the progress sidebar on the right.
   */
  public function actionIndex() {

    // Retrieve all user slots with their projects.
    $slots = array();
    if (!Yii::app()->user->isGuest) {
      $slots = $this->slots_load_from_user();
    }

    // Get the default slots if the user has no projects.
    if (count($slots)==0)
      $slots = $this->slots_get_default();
    
    // Render on the view.
    $this->render('index', array('slots'=>$slots));
  }

  /**
   * Retrieve default slots for the empty positions, and fill them with sample data.
   * @return array An array with Project models with example data for all the free positions.
   */
  private function slots_get_default($models=null) {

    // Place new default slots inside this array.
    $slots = array();

    // Put inside an array all the positions that are occupied.
    $found_positions = array();
    if (is_array($models)) {
      foreach ($models as $model) {
        $found_positions[] = $model->position;
      }
      Yii::log('slots_get_default: occupied slots: '.implode(',',$found_positions), 'trace');
    } else {
      Yii::log('slots_get_default: there are no occupied slots', 'trace');
    }

    // Put inside an array all positions that must be filled with data.
    $max_slots = array();
    for ($i=1;$i<=self::MAX_SLOTS;$i++)
      $max_slots[] = $i;
    Yii::log('slots_get_default: max slots: '.implode(',',$max_slots), 'trace');

    // Get the difference between the total of slots and the found slots, that's what we must fill with default values.
    $free_slots = array_diff($max_slots, $found_positions);
    
    // Fill all the free positions with example data.
    if (is_array($free_slots)) {
      foreach ($free_slots as $free_position) {
        $slots[$free_position] = Project::defaultOne($free_position);
      }
      Yii::log('slots_get_default: filled the following free with example data: '.implode(',',$free_slots), 'trace');
    }
    return $slots;
  }

  /**
   * Load all the slots with the projects belonging to the logged user.
   * @return array All the projects of the user.
   */
  private function slots_load_from_user() {
    Yii::log('slots_load_from_user: finding slots', 'trace');

    // Get params and look for projects in the database.
    $slots = array();
    $id_user = (int)Yii::app()->user->id;
    $models = Project::model()->findAll("id_user=$id_user AND archived=0");
    
    // If there are projects found, then create a slots array and store each project in their current position.
    if (is_array($models) && count($models) > 0) {
      foreach ($models as $model) {
        $slots[$model->position] = $model;
      }
    }

    // Count all the results fount, and if there are less than the max slots, then fill the free ones with default values.
    $found = count($slots);
    Yii::log("slots_load_from_user: found $found slots", 'trace');
    if ($found<self::MAX_SLOTS) {
      Yii::log("found less slots than max. let's fill the rest with default values", 'trace');
      $default_slots = $this->slots_get_default($models);
      $slots = $slots+$default_slots; // Sum, don't array_merge, this way you'll keep index keys.
    }
    
    // Now sort the slots array to have it displayed in the correct order on the screen.
    ksort($slots);
    return $slots;
  }

  /**
   * Update the name of a slot.
   */
  public function actionUpdate_slot_name() {

    // Get params.
    $id_user = (int)Yii::app()->user->id;
    $position = (int)str_replace('slot_name_','',$_POST['id']);
    $value = $_POST['value'];

    // Find the project by user and position.
    $slot = Project::model()->find("id_user=$id_user AND position=$position");

    // Nothing found, create a new one.
    if ($slot==null) {
      Yii::log('actionUpdate_slot_name: not found, creating new', 'trace');
      $slot=new Project();
      $slot->id_user = $id_user;
      $slot->position = $position;
    } else {
      Yii::log('actionUpdate_slot_name: project found, id: '.$slot->id_project, 'trace');
    }

    // Set the new name and update the model.
    $slot->name=$value;
    if ($slot->save()) {
      echo $slot->name;
    } else {
      echo 'error al guardar..';
      Yii::log('actionUpdate_slot_name: error saving: '.$slot->id_project, 'error');
    }
  }

  /**
   * Update the details of a slot.
   */
  public function actionUpdate_slot_details() {

    // Get params.
    $id_user = (int)Yii::app()->user->id;
    $position = (int)str_replace('slot_details_','',$_POST['id']);
    $value = $_POST['value'];

    // Find the project by user and position.
    $slot = Project::model()->find("id_user=$id_user AND position=$position");
    if ($slot==null) {
      $slot=new Project();
      $slot->id_user = $id_user;
      $slot->position = $position;
    }

    // Set the new details and update the model.
    $slot->details=$value;
    if ($slot->save()) {
      echo Tools::slot_detail_nl2br($slot->details);
    } else {
      echo 'error al guardar..';
    }
  }

  /**
   * Refresh the progress sidebar.
   */
  public function actionRefresh_progress() {
    $params = array();
    if (isset($_POST['add'])) {
      $add = trim($_POST['add']);
      $id_user = (int)Yii::app()->user->id;
      $position = (int)str_replace('slot_progress_','',$_POST['id']);
      $slot = Project::model()->find("id_user=$id_user AND position=$position");
      if ($slot!=null) {
        $progress = new Progress();
        $progress->id_project=$slot->id_project;
        $progress->details=$add;
        $progress->timestamp=time();
        $progress->save();
        $params['id_added_new'] = $progress->id_progress;
      }
    }
    if (isset($_POST['delete'])) {
      $id_progress = (int)str_replace('delete_progress_','',$_POST['delete']);
      Progress::model()->deleteByPk($id_progress);
    }
    $this->widget('application.components.ProgressWidget', $params);
  }

  /**
   * Displays the contact page
   */
  public function actionContact() {
    $contact=new ContactForm;
    if(isset($_POST['ContactForm'])) {
      $contact->attributes=$_POST['ContactForm'];
      if($contact->validate()) {
        $headers="From: {$contact->email}\r\nReply-To: {$contact->email}";
        mail(Yii::app()->params['adminEmail'],$contact->subject,$contact->body,$headers);
        Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
        $this->refresh();
      }
    }
    $this->render('contact',array('contact'=>$contact));
  }

  /**
   * Displays the register page
   */
  public function actionRegister() {
    $register=new RegisterForm;
    if(isset($_POST['RegisterForm'])) {
      $register->attributes=$_POST['RegisterForm'];
      if($register->validate()) {
        $register->addUser();
//				$headers="From: {$register->email}\r\nReply-To: {$register->email}";
//				mail(Yii::app()->params['adminEmail'],$register->subject,$register->body,$headers);
        Yii::app()->user->setFlash('register','Cuenta creada, ahora ya puedes entrar.');
        $this->refresh();
      }
    }
    $this->render('register',array('register'=>$register));
  }

  /**
   * Displays the login page
   */
  public function actionLogin() {
    $form=new LoginForm;
    // collect user input data
    if(isset($_POST['LoginForm'])) {
      $form->attributes=$_POST['LoginForm'];
      // validate user input and redirect to previous page if valid
      if($form->validate())
        $this->redirect(Yii::app()->user->returnUrl);
    }
    // display the login form
    $this->render('login',array('form'=>$form));
  }

  /**
   * Logout the current user and redirect to homepage.
   */
  public function actionLogout() {
    Yii::app()->user->logout();
    $this->redirect(Yii::app()->homeUrl);
  }
}